<?php

namespace App\Http\Controllers\Dynamic;

use App\LogicService\Contracts\SamGlucoseLogicContract;
use App\Models\Dynamic\SamWear;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;

class SamWearController extends ApiController
{
    /**
     * @var \App\Models\Dynamic\SamWear
     */
    protected $samWear;

    protected $request;

    protected $user;

    protected $samGlucose;

    /**
     * samWearController constructor.
     * @param \App\Models\Dynamic\SamWear $samWear
     * @param \Illuminate\Http\Request $request
     */
    public function __construct(SamWear $samWear, User $user,
                                Request $request,SamGlucoseLogicContract $samGlucose)
    {
        parent::__construct();

        $this->samWear = $samWear;
        $this->request = $request;
        $this->samGlucose = $samGlucose;
        $this->user = $user;

    }

    /**
     * samWearController index.
     * @return \Illuminate\Http\JsonResponse
     */

    public function index()
    {
        $this->validate($this->request, [
            'user_id' => 'required|integer'
        ]);

        $user_id = $this->request->input('user_id');
        $user = $this->user
            ->withoutGlobalScopes()
            ->select('id', 'account')
            ->find($user_id);

        $data = $this->samWear->where('userid', '=', $user->id)
            ->select(['id','starttime', 'endtime', 'emittercode', 'sensorcode', 'status'])
            ->orderBy('id', 'desc')
            ->get()
            ->toArray();

        return $this->response($data);


    }


    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function getListInfo()
    {

        $this->validate($this->request, [
            'user_id' => 'required|integer'
        ]);

        $user_id = $this->request->input('user_id');
        $user = $this->user
            ->withoutGlobalScopes()
            ->select('id', 'account')
            ->find($user_id);

        $data = $this->samWear->where('userid', '=', $user->id)
            ->select(['id','starttime', 'endtime', 'emittercode', 'sensorcode', 'status'])
            ->orderBy('id', 'desc')
            ->get()
            ->toArray();


        if ($data) {
            foreach ($data as $k => $v) {
                if (!$v['endtime']) {
                    $v['endtime'] = Carbon::now()->toDateTimeString();
                }
                $data[$k]['data'] = $this->samGlucose->getAllWearData($user_id, $v['starttime'], $v['endtime']);
            }
        }

        return $this->response($data);
    }





}
